package com.lzx.reggie.service.impl

import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.lzx.reggie.common.CustomException
import com.lzx.reggie.dto.SetmealDto
import com.lzx.reggie.entity.Setmeal
import com.lzx.reggie.entity.SetmealDish
import com.lzx.reggie.mapper.SetmealMapper
import com.lzx.reggie.service.SetmealDishService
import com.lzx.reggie.service.SetmealService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional


@Service
class SetmealServiceImpl : ServiceImpl<SetmealMapper, Setmeal>(), SetmealService {
    @Autowired
    private lateinit var setmealDishService: SetmealDishService

    /**
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     * @param setmealDto
     */
    @Transactional
    override fun saveWithDish(setmealDto: SetmealDto) {
        //保存套餐的基本信息，操作setmeal，执行insert操作
        save(setmealDto)
        val setmealDishes = setmealDto.setmealDishes
        setmealDishes!!.map { item: SetmealDish ->
            item.setmealId = setmealDto.id
            item
        }
        //保存套餐和菜品的关联信息，操作setmeal_dish,执行insert操作
        setmealDishService.saveBatch(setmealDishes)
    }

    /**
     * 删除套餐，同时需要删除套餐和菜品的关联数据
     * @param ids
     */
    @Transactional
    override fun removeWithDish(ids: List<Long>) {

        //查询套餐状态，确定是否可用删除
        val count = this.count(
            //select count(*) from setmeal where id in (1,2,3) and status = 1
            KtQueryWrapper(Setmeal::class.java).apply {
                `in`(Setmeal::id, ids)
                eq(Setmeal::status, 1)
            })
        if (count > 0) {
            //如果不能删除，抛出一个业务异常
            throw CustomException("套餐正在售卖中，不能删除")
        }

        //如果可以删除，先删除套餐表中的数据---setmeal
        removeByIds(ids)

        //删除关系表中的数据----setmeal_dish
        setmealDishService.remove(
            //delete from setmeal_dish where setmeal_id in (1,2,3)
            KtQueryWrapper(SetmealDish::class.java).apply {
                `in`(SetmealDish::setmealId, ids)
            })
    }
}
